<template>
  <div class="cart-container">
    <Spin fix size="large" v-if="loading"></Spin>

    <div id="cartBtn" class="cart-btn cursor"
         :class="{'active': parseInt(cartTotal) > 0}"
         v-if="!cartModal.is"
         @click="cartModal.is = cartModal.list.length > 0">
      <span v-if="cartTotal > 0">{{ cartTotal }}</span>
    </div>
    <!--购物车弹窗-->
    <div class="model cart-model" :class="{'show': cartModal.is}" @click="cartModal.is = false">
      <div class="cart-body">
        <div class="close-arrow iconfont icon-youjiantou cursor" @click="cartModal.is = false"></div>
        <div class="cart-content" @click.stop>
          <div class="cart-list">
            <div class="cart-group" v-for="(item, index) in cartModal.list" :key="index">
              <div class="item flex">
                <div class="icon-check" :class="{checked: item.checked}" @click="item.checked = !item.checked"></div>
                <c-image :url="item.imgUrl" :alt="item.name" width="80px" height="80px" radio="4px"/>
                <div class="cart-goods flex-column flex-1 row-between">
                  <div>
                    <div class="name fz-16 line-clamp">{{ item.name }}</div>
                    <div class="sku color-muted fz-12 mt-5">{{ item.skuNames }}</div>
                  </div>
                  <div class="cart-goods-bottom flex col-center row-between">
                    <div class="number-control">
                      <div class="minus iconfont icon-jian" @click="editCart(item, index, -1)"></div>
                      <input type="number" v-model="item.number" :min="0" :max="99" @blur="cartNumberChange(item, index)">
                      <div class="add iconfont icon-jia" @click="editCart(item, index, 1)"></div>
                    </div>
                    <div class="price">{{ item.price }}</div>
                  </div>
                </div>
              </div>
              <div class="cart-children">
                <div class="children-item flex" v-for="(child, childIndex) in item.packageList" :key="childIndex">
                  <c-image :url="child.imgUrl" :alt="child.name" width="60px" height="60px" radio="4px"/>
                  <div class="children-info">
                    <div class="name line-clamp">{{child.name}}</div>
                    <div class="price">{{child.price}}</div>
                  </div>
                </div>
              </div>
            </div>
            <div style="height: 150px"></div>
          </div>
          <div class="cart-footer flex-column row-between">
            <div class="flex row-between col-base">
              <span class="color-gray">已选：{{ cartTotal }}件</span>
              <span class="flex col-base">合计：<span class="price">{{ totalPrice }}</span></span>
            </div>
            <div class="flex row-between col-center">
              <Button type="primary" long @click="settlement">结算</Button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--规格弹窗-->
    <sku-model v-model="skuModal.is"
               :list="skuModal.skuList"
               :package-data="skuModal.packageList"
               :cartList="cartModal.list"
               :goods-item="skuModal.goodsItem"
               @buy="(params) => this.$refs.settlement.settlementSku(params)"
               @addCart="skuAddCart"
    />
    <!--结算-->
    <settlement ref="settlement" @success="paySuccess"/>
  </div>
</template>
<script>
import {goodsDetail, goodsTaste} from "@/api/goods";
import settlement from "./settlement.vue";
import SkuModel from "@/views/shop/components/skuModel.vue";

export default {
  name: "cart",
  components: {
    SkuModel,
    settlement
  },
  data() {
    return {
      cartModal: {
        is: false,
        list: [],
      },
      skuModal: {
        is: false,
        skuList: [],
        goodsItem: {},
      },
      moveRunning: false,
      checkList: [],
      loading: false,
    }
  },
  computed: {
    checkedList() {
      return this.cartModal.list.filter(item => item.checked)
    },
    totalPrice() {
      const money = this.checkedList.reduce((total, curr) => {
        return total + (curr.number * curr.price)
      }, 0)
      return Math.abs(money.toFixed(2))
    },
    cartTotal() {
      const num = this.checkedList.reduce((pre, curr) => {
        pre = parseInt(pre)
        curr.number = parseInt(curr.number)
        return (isNaN(pre) ? 0 : pre) + (isNaN(curr.number) ? 0 : curr.number)
      }, 0)
      return num;
    },
  },
  methods: {
    goodsStock(goods) {
      const number = this.cartModal.list.reduce((pre, curr) => {
        return pre + (curr.id == goods.id ? curr.number : 0)
      }, 0)
      return goods.stockCount - number
    },
    // 添加购物车获取规格
    addCart(item) {
      if (this.goodsStock(item) <= 0) {
        this.$Message.error('商品已售罄')
        return false
      }
      this.getDetail(item)
    },
    getDetail(item) {
      this.loading = true
      goodsDetail({goodsId: item.id}).then(res => {
        if (res.code != 200) {
          this.$Message.error(res.msg || '获取商品信息失败')
          return false
        }
        let data = res.data
        data.stockCount = data.stockCount == null ? 999: data.stockCount
        let tasteList = this.formatSkuRes(data.tasteList || [])
        let packageList = data.packageList || null
        if (tasteList.length || packageList.length) {
          data.isPackage = item.isPackage
          this.skuModal = {
            is: true,
            goodsItem: data,
            skuList: tasteList,
            packageList: packageList,
          }
          return
        }
        console.log(res)
        this.bindCartData(item)
      }).finally(() => {
        this.loading = false
      })
    },
    formatSkuRes(list) {
      return list.map(taste => {
        if (taste.type == 1) {
          let disableNum = 0;
          taste.children.map(s => {
            s.disabled = s.stockNumber != null && s.stockNumber <= 0
            s.active = s.isChecked == 1 && !s.disabled
            if (s.disabled) {
              disableNum++
            }
            return s
          })
          taste.label = taste.checkNumber < 99 ? `以下${taste.children.length}选${taste.checkNumber}`: ''
          taste.isRequired = disableNum == taste.children.length ? 0: taste.isRequired
        } else {
          taste.active = false
        }
        return taste
      });
    },
    skuAddCart(data) {
      this.bindCartData(data.goodsItem, data, data.number)
    },
    cartNumberChange(item, index) {
      if (!item.number) item.number = 1
      let num = item.number + ''.split('.')
      num = !num[1] ? (num[0] + '.00') : num
      item.number = parseInt(num).toFixed(0)
      item.number = Math.min(item.number, item.goodsInfo.stockCount)
      if (item.number <= 0) {
        this.editCart(item, index, 0)
      }
    },
    editCart(item, index, number) {
      item.number += number
      item.number = Math.min(item.number, item.goodsInfo.stockCount)
      if (item.number <= 0) {
        this.cartModal.list.splice(index, 1)
      }
      if (this.cartModal.list.length <= 0) {
        this.cartModal.is = false
      }
    },
    bindCartData(item, skuData = {}, number = 1) {
      if (this.moveRunning) return
      let obj = {
        id: item.id,
        name: item.name,
        checked: true,
        goodsInfo: item,
        price: skuData.skuPriceInfo ? skuData.skuPriceInfo.price : item.price,
        otPrice: skuData.skuPriceInfo ? skuData.skuPriceInfo.otPrice : item.otPrice,
        number: (item.number || 0),
        imgUrl: item.imgUrl,
        canCardPay: item.canCardPay,
        skuIds: skuData.skuIds || '',
        skuNames: skuData.skuNames || '',
        skuList: (skuData.skuList || []).map(sku => {
          return {
            goodsId: sku.goodsId,
            id: sku.id,
            name: sku.name,
            goodsName: sku.goodsName,
            price: sku.price,
            type: sku.type,
            isRequired: sku.isRequired,
            parentId: sku.parentId,
            consumedNumber: sku.consumedNumber
          }
        }),
        isPackage: item.isPackage,
        packageList: skuData.packageList || [],
      }
      let cart = this.cartModal.list.find(cart => cart.id == item.id && cart.skuIds == obj.skuIds);
      if (cart) {
        cart.number += number
        cart.skuList = cart.skuList.concat(skuData.skuList || [])
        item.number += number
      } else {
        obj.number = number
        this.cartModal.list.push(obj)
        item.number = obj.number
      }
      this.cartMove(item, obj.skuIds || '', skuData.moveEl)
    },
    cartMove(item, skuIds, moveEl) {
      let boundBtn = null
      let left = 0
      if (moveEl) {
        boundBtn = document.getElementById(moveEl).getBoundingClientRect()
        left = 40
      } else {
        boundBtn = document.getElementById(`goods${item.id}`).getBoundingClientRect()
      }
      if (!boundBtn) return
      let boundCart = document.getElementById('cartBtn').getBoundingClientRect()
      let flyItem = document.getElementById('flyItem')
      let flyIcon = document.getElementById('flyIcon')

      let offsetX = boundCart.left + boundCart.width / 2 - (boundBtn.left - left + boundBtn.width / 2)
      let offsetY = boundCart.top + boundCart.height / 2 - (boundBtn.top + boundBtn.height / 2)

      flyItem.style.display = 'block'
      flyItem.style.left = (boundBtn.left) + 'px'
      flyItem.style.top = (boundBtn.top) + 'px'
      this.moveRunning = true
      setTimeout(() => {
        flyItem.style.transform = 'translateX('+ offsetX +'px)';
        flyIcon.style.transform = 'translateY('+ offsetY +'px)';
        setTimeout(() => {
          flyItem.style.display = ''
          flyItem.style.transform = 'translateX(0)';
          flyIcon.style.transform = 'translateY(0)';
          this.moveRunning = false
        }, 490)
      }, 10)
    },
    settlement() {
      this.$refs.settlement.settlementCart(this.cartModal)
    },
    paySuccess() {
      this.cartModal = {
        is: false,
        list: [],
      }
      this.skuModal = {
        is: false,
        list: [],
        goodsItem: {},
        number: 1
      }
    }
  },
}
</script>

<style scoped lang="scss">
@import "cart";
</style>
